﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using FCDB.Entity;
using FCDB.Repository;
using FCDB.Web.Models;
using FCDB.Entity.EntityEx;
using FCDB.Entity.Enum;
using System.Web.Security;
using System.Configuration;
using FB.Services;
using FB.Providers;
using FB.Enums;
using FB.Providers.EmployeeInfo;
using FB.Mvc.Controllers;
using System.Linq.Expressions;
using FB.Membership;

namespace FCDB.Web.Controllers
{
      [FB.Membership.Annotations.AuthorizeOnly]
    public class EmployeeController : BaseController
    {
        private MyTeamRepository respository = new MyTeamRepository();
        public ActionResult Index()
        {
            if (Request.IsAjaxRequest())
            {
                var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
                EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit(); 
                int total = 0, take = 10, skip = 0;
                int.TryParse(Request["take"], out take);
                int.TryParse(Request["skip"], out skip);
                IList<Expression<Func<Employee, bool>>> fiters = new List<Expression<Func<Employee, bool>>>();
                fiters.Add(t => t.RecordState == RecordState.Active);
                if(!string.IsNullOrEmpty(Request["keyword"]))
                {
                    string ky = Request["keyword"];
                    fiters.Add(t => t.ChineseName.IndexOf(ky) > -1);
                }
                IList<Employee> list = unitinfo.EmployeeRepository.GetPagedListByFilters(fiters,
                    m => m.OrderByDescending(x => x.CreatedDate), skip / take, take, out total).ToList();
                IList<EmployeeModel> modelList = new List<EmployeeModel>();
                foreach (Employee item in list)
                {
                    modelList.Add(new EmployeeModel(item));
                }
                PagerModel model = new PagerModel()
                {
                    Data = modelList,
                    TotalCount = total
                };
                JsonResult json = new JsonResult()
                {
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                    Data = model
                };
                return json;
            }
            return View();
        }


        public ActionResult Create()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit(); 
            if (string.IsNullOrEmpty(Request["ID"]))
            {
                Employee entity = new Employee();
                entity.PostDetails = new List<EmployeeInPosition>();
                entity.Supervisors = new List<Employee>(); 
                List<SelectListItem> EmployeeTypeSelectedList = new List<SelectListItem>();
                List<EmployeeType> EmployeeTypeList = unitinfo.EmployeeTypeRepository.Get(null).ToList();
                foreach (EmployeeType item in EmployeeTypeList)
                {
                    SelectListItem selectedItem = new SelectListItem()
                    {
                        Text = item.Name,
                        Value = item.EMPType
                    };
                    EmployeeTypeSelectedList.Add(selectedItem);
                }
                ViewBag.EmployeeTypeList = EmployeeTypeSelectedList;
                ViewBag.CompanyList = unitinfo.CompanyRepository.Get(t => t.RecordState == RecordState.Active  , m => m.OrderBy(t => t.Order)).ToList();
                ViewBag.PositionList = unitinfo.PositionRepository.Get(t => t.RecordState == RecordState.Active, m => m.OrderBy(t => t.Order)).ToList();
                ViewBag.DepartmentList = new List<Department>();
                ViewBag.TeamList = new List<SelectListItem>(); 
                return View(entity);
            }
            else
            {
                string id = Request["ID"];
                Employee entity =unitinfo.EmployeeRepository.GetByKey(id);
                List<EmployeeType> EmployeeTypeList = unitinfo.EmployeeTypeRepository.Get(null).ToList();
                List<SelectListItem> EmployeeTypeSelectedList = new List<SelectListItem>();
                foreach (EmployeeType item in EmployeeTypeList)
                {
                    SelectListItem selectedItem = new SelectListItem()
                    {
                        Text = item.Name,
                        Value = item.EMPType,
                        Selected = item.EMPType == entity.EMPType
                    };
                    EmployeeTypeSelectedList.Add(selectedItem);
                }
                ViewBag.EmployeeTypeList = EmployeeTypeSelectedList;
                ViewBag.CompanyList = unitinfo.CompanyRepository.Get(t => t.RecordState == RecordState.Active , m => m.OrderBy(t => t.Order)).ToList();
                ViewBag.PositionList = unitinfo.PositionRepository.Get(t => t.RecordState == RecordState.Active, m => m.OrderBy(t => t.Order)).ToList();
                ViewBag.DepartmentList = new List<Department>();
                ViewBag.TeamList = new List<SelectListItem>(); 
        
                return View(entity);
               
            }
        }
        /// <summary>
        /// 选择岗位
        /// </summary>
        /// <returns></returns>
        public ActionResult UCPostSelect()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            IList<Position> structureList = unitinfo.PositionRepository.Get(t => t.RecordState == RecordState.Active, m => m.OrderBy(t => t.Order)).ToList();
            return View(structureList);
        }
          
       
        /// <summary>
        /// 保存雇员信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Save(Employee model,  string strEmployeeInPositions,string strSupervisors,HttpPostedFileBase Imgfile)
        {
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            IList<Employee> Supervisors = jsonConverter.Deserialize<IList<Employee>>(strSupervisors); 
            IList<EmployeeInPosition> EmployeeInPositionList = jsonConverter.Deserialize<IList<EmployeeInPosition>>(strEmployeeInPositions); 
            var EF = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit infoUnit = EF.GetEmployeeInfoUnit();
            EmployeeInfoService  EmployeeInfoService=  EmployeeInfoManager.GetEmployeeInfoService(infoUnit);

            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            // 验证登录名和邮件重复
            EmployeeInfoService unitinfo = efemployeeInfoProvider.GetEmployeeInfoService();
            Employee User = unitinfo.GetEmployeeByUserName(model.UserName);
            if (User != null && User.EMPCode != model.EMPCode)
                return Json("登录名重复" );

            //   IQueryable<Employee> Users = infoUnit.EmployeeRepository.Get(t => t.Email == model.Email && t.UserID != null);
          //  if (Users.Count() != 0)
         //       return Json("邮件名重复");

            if (string.IsNullOrEmpty(model.EMPCode))
            { 
                model.EMPCode = EmployeeInfoService.GenerateEMPCode(model.EMPType); 
                string defaultPwd = ConfigurationManager.AppSettings["DefaultUserPassword"].ToString();
                model.Supervisors = new List<Employee>();
                foreach (Employee item in Supervisors)
                    model.Supervisors.Add(infoUnit.EmployeeRepository.GetByKey(item.EMPCode));
                if (EmployeeInPositionList.Count() > 0)
                {
                    EmployeeInPositionList.First().IsPrimary = true;
                }
               
                MembershipUser user = null;
                
                user = Membership.CreateUser(model.UserName, defaultPwd, model.Email); 
                model.UserID = (Guid)user.ProviderUserKey;
                model.UserName = user.UserName; 
                foreach (var item in EmployeeInPositionList)
                {
                    item.EMPCode = model.EMPCode; 
                }
                foreach (Employee item in Supervisors)
                {
                    model.Supervisors.Add(infoUnit.EmployeeRepository.GetByKey(item.EMPCode));
                }
                if (Imgfile != null)
                {
                    ProfilePic newFile = new ProfilePic();
                    newFile.EMPCode = model.EMPCode;
                    newFile.ProfileImage = new byte[Imgfile.ContentLength];
                    Imgfile.InputStream.Read(newFile.ProfileImage, 0, (int)Imgfile.ContentLength);
                    unitinfo.CreateEmployeePhoto(newFile.EMPCode, newFile.ProfileImage);
                }
                model.PostDetails = EmployeeInPositionList;
                infoUnit.EmployeeRepository.Insert(model);
                infoUnit.SaveChanges();

            }
            else
            {
                Employee employee = infoUnit.EmployeeRepository.GetByKey(model.EMPCode);
                
                employee.Supervisors.Clear();
                foreach (Employee item in Supervisors)
                {
                    model.Supervisors.Add(infoUnit.EmployeeRepository.GetByKey(item.EMPCode));
                }
                while (employee.PostDetails.Count > 0)
                {
                    var item = employee.PostDetails.ToList()[0];
                    infoUnit.EmployeeInPositionRepository.Delete(item);
                }
              
                foreach (var item in EmployeeInPositionList)
                {
                    item.EMPCode = model.EMPCode;
                    employee.PostDetails.Add(item);
                }
                if (employee.PostDetails.Count > 0)
                {
                    employee.PostDetails.First().IsPrimary = true;
                }
                employee.Alias = model.Alias;
                employee.ChineseName = model.ChineseName;
                employee.Mobile = model.Mobile;
                employee.Email = model.Email;
                employee.EmployeeType = model.EmployeeType;
                employee.EMPType = model.EMPType;
                employee.FirstName = model.FirstName;
                employee.Gender = model.Gender;
                employee.LastName = model.LastName;
                employee.RefCode = model.RefCode;
                employee.ExtensionNo = model.ExtensionNo;
                employee.TerminationDate = model.TerminationDate;
                if (Imgfile != null)
                {
                    ProfilePic newFile = new ProfilePic();
                    newFile.EMPCode = model.EMPCode;
                    newFile.ProfileImage = new byte[Imgfile.ContentLength];
                    Imgfile.InputStream.Read(newFile.ProfileImage, 0, (int)Imgfile.ContentLength);
                    unitinfo.UpdateEmployeePhoto(newFile.EMPCode, newFile.ProfileImage);
                }
                infoUnit.EmployeeRepository.Update(employee);
                infoUnit.SaveChanges();
            }
            return null;
        }

        public ActionResult GetImg()
        {
            string id = Request["ID"];
            if (string.IsNullOrEmpty(id)) return Json(null);
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            EmployeeInfoService unitService = efemployeeInfoProvider.GetEmployeeInfoService();
            Employee PeopleInfo = unitinfo.EmployeeRepository.Get(t => t.UserID == new Guid(id) && t.UserID != null).First();
            byte[] imageByte = unitService.GetEmployeePhoto(PeopleInfo.EMPCode);
            if (imageByte != null)
            {
                return new FileContentResult(imageByte, "image/jpeg");
            }
            return Json("");
        }

        public ActionResult UploadImage()
        {
            byte[] b = new byte[Request.Files[0].ContentLength];
            Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
            Session["ContentStream"] = b;
            return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);

        }
        public ActionResult GetUploadImage()
        {
            byte[] ImgByte = (byte[])Session["ContentStream"];
            Session["ContentStream"] = "";
            return new FileContentResult(ImgByte, "image/jpeg");

        }
        public ActionResult Delete(string rpValue)
        {

            string[] ids = rpValue.Split(",".ToArray());
            if (ids.Length == 0) return null;
            var EF = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit infoUnit = EF.GetEmployeeInfoUnit();
            foreach (string item in ids)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    Employee employee = infoUnit.EmployeeRepository.GetByKey(item);
                    employee.RecordState = RecordState.Deleted;
                    infoUnit.EmployeeRepository.Update(employee);
                }
            }
            infoUnit.SaveChanges();
            return null;
        }

        /// <summary>
        /// 获取组
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTeams()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit(); 
            string DepartmentID = Request["DepartmentID"];
            List<Team> team = new List<Team>();
            if (string.IsNullOrEmpty(DepartmentID))
            {
                return Json(team, JsonRequestBehavior.AllowGet);
            }
            team = unitinfo.TeamRepository.Get(t => t.RecordState == RecordState.Active && t.DEPTCode == DepartmentID, m => m.OrderBy(t => t.Order)).ToList();
            IList<TeamModel> teamModelList = new List<TeamModel>();
            foreach (var item in team)
            {
                teamModelList.Add(new TeamModel(item));
            }
            return Json(teamModelList, JsonRequestBehavior.AllowGet);
         
        }

        /// <summary>
        /// 获取部门
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeparmentList()
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit(); 
            string CompanyID = Request["CompanyID"];
            List<Department> departments = new List<Department>();
            if (string.IsNullOrEmpty(CompanyID))
            {
                return Json(departments, JsonRequestBehavior.AllowGet);
            }
            departments = unitinfo.DepartmentRepository.Get(t => t.RecordState == RecordState.Active   && t.COMCode == CompanyID, m => m.OrderBy(t => t.Order)).ToList();
              
            return PartialView("UCDepartmentSelectTree", departments);
        }


        public ActionResult EmployeeSelect(string strUserIDList,string Lock)
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IList<Company> structureList = unitinfo.CompanyRepository.Get(t => t.RecordState == RecordState.Active  , m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>(); 
                    foreach (Company item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.COMCode,
                            Value = "Company"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Company",
                            Name = item.Name,
                            spriteCssClass = "treeView_Company"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion 
                #region 点击公司节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Company")
                {
                    IList<Department> deptList = unitinfo.DepartmentRepository.Get(t => t.RecordState == RecordState.Active &&t.COMCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.DEPTCode,
                            Value = "Department"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Department",
                            Name = item.Name,
                            spriteCssClass = "treeView_Department"
                        };
                        EmployeeModelList.Add(model); 
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion 
                #region 点击部门节点
                if (keyvalueModel.Value == "Department")
                {
                    IList<Team> teamList = unitinfo.TeamRepository.Get(t => t.RecordState == RecordState.Active && t.DEPTCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in teamList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.TEAMCode,
                            Value = "Team"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Team",
                            Name = item.Name,
                            spriteCssClass = "treeView_Team"
                        };
                        EmployeeModelList.Add(model);
                       
                    }
                    IList<EmployeeInPosition> employeePostList = unitinfo.EmployeeInPositionRepository.Get(t => t.DEPTCode == keyvalueModel.Key).ToList();
                    foreach (var item in employeePostList)
                    {

                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = unitinfo.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                             UserID=employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion 
                #region 展开分组
                if (keyvalueModel.Value == "Team")
                { 
                    IList<EmployeeInPosition> employeePostList = unitinfo.EmployeeInPositionRepository.Get(t => t.TEAMCode == keyvalueModel.Key).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    { 
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = unitinfo.EmployeeRepository.GetByKey(item.EMPCode);
                       
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion 
            }
            if (!string.IsNullOrEmpty(strUserIDList))
            {
                IList<Guid> UserIDList = jsonConverter.Deserialize<List<Guid>>(strUserIDList);
                IList<Employee> EmployeeList=new List<Employee>();
                foreach(Guid item in UserIDList)
                {
                    Employee employeeItem=GetEmployeeByUserKey(item);
                    EmployeeList.Add(employeeItem);
                }
                ViewBag.EmployeeList = EmployeeList;
            }
            if (!string.IsNullOrEmpty(Lock))
            {
                if (Lock.Trim() == "True")
                    ViewBag.Lock = "True";
            }
            return View(); 
        }

        public ActionResult RoleSelect(string strUserIDList)
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IEnumerable<string> structureList = wapper.FindAll();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (string item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item,
                            Value = "Role"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Role",
                            Name = item,
                            spriteCssClass = "treeView_Role"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击角色节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Role")
                {
                    IEnumerable<string> deptList = wapper.FindUserNamesByRole(keyvalueModel.Key);
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        Employee i = GetEmployeeByUserName(item);
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = i.ChineseName,
                            spriteCssClass = "treeView_Employee",
                             UserID=i.UserID,
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 展开分组
                if (keyvalueModel.Value == "User")
                {
                    IList<EmployeeInPosition> employeePostList = unitinfo.EmployeeInPositionRepository.Get(t => t.TEAMCode == keyvalueModel.Key).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = unitinfo.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            if (!string.IsNullOrEmpty(strUserIDList))
            {
                IList<Guid> UserIDList = jsonConverter.Deserialize<List<Guid>>(strUserIDList);
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (Guid item in UserIDList)
                {
                    Employee employeeItem = GetEmployeeByUserKey(item);
                    EmployeeList.Add(employeeItem);
                }
                ViewBag.EmployeeList = EmployeeList;
            }
            return View();
        }
        public ActionResult DeparmentSelect(string strUserIDList)
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  第一次加载
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    IList<Company> structureList = unitinfo.CompanyRepository.Get(t => t.RecordState == RecordState.Active , m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Company item in structureList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.COMCode,
                            Value = "Company"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Company",
                            Name = item.Name,
                            spriteCssClass = "treeView_Company"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击公司节点
                string ID = Request["ObjectID"];
                KeyValueModel keyvalueModel = jsonConverter.Deserialize<KeyValueModel>(ID);
                if (keyvalueModel.Value == "Company")
                {
                    IList<Department> deptList = unitinfo.DepartmentRepository.Get(t => t.RecordState == RecordState.Active  && t.COMCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in deptList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.DEPTCode,
                            Value = "Department"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Department",
                            Name = item.Name,
                            spriteCssClass = "treeView_Department"
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 点击部门节点
                if (keyvalueModel.Value == "Department")
                {
                    IList<Team> teamList = unitinfo.TeamRepository.Get(t => t.RecordState == RecordState.Active && t.DEPTCode == keyvalueModel.Key, m => m.OrderBy(t => t.Order)).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in teamList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.TEAMCode,
                            Value = "Team"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = true,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Team",
                            Name = item.Name,
                            spriteCssClass = "treeView_Team"
                        };
                        EmployeeModelList.Add(model);

                    }
                    IList<EmployeeInPosition> employeePostList = unitinfo.EmployeeInPositionRepository.Get(t => t.DEPTCode == keyvalueModel.Key).ToList();
                    foreach (var item in employeePostList)
                    {

                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = unitinfo.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
                #region 展开分组
                if (keyvalueModel.Value == "Team")
                {
                    IList<EmployeeInPosition> employeePostList = unitinfo.EmployeeInPositionRepository.Get(t => t.TEAMCode == keyvalueModel.Key).ToList();
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (var item in employeePostList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        string id = jsonConverter.Serialize(keyValueModel);
                        if (EmployeeModelList.Count(t => t.ObjectID == id) > 0) continue;
                        Employee employee = unitinfo.EmployeeRepository.GetByKey(item.EMPCode);
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = employee.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = employee.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            if (!string.IsNullOrEmpty(strUserIDList))
            {
                IList<Guid> UserIDList = jsonConverter.Deserialize<List<Guid>>(strUserIDList);
                IList<Employee> EmployeeList = new List<Employee>();
                foreach (Guid item in UserIDList)
                {
                    Employee employeeItem = GetEmployeeByUserKey(item);
                    EmployeeList.Add(employeeItem);
                }
                ViewBag.EmployeeList = EmployeeList;
            }
            return View();
        }
        public ActionResult SelectEmployees(string strUserIDList)
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  搜索
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    string Key = Request["Key"] ?? "";
                    var TrimedKey = Key.Replace(" ", string.Empty);
                    
                    //IList<Employee> EmployeeList = unitinfo.EmployeeRepository.Get(t => t.ChineseName.IndexOf(Key) > -1).ToList() ;

                    IList<Employee> EmployeeList = unitinfo.EmployeeRepository.Get(t => t.UserID != null && (t.UserID != null && (t.ChineseName.IndexOf(Key) > -1 || t.UserName.IndexOf(Key) > -1 || t.EMPCode.IndexOf(Key) > -1 || t.RefCode.IndexOf(Key) > -1)))
                        .ToList();

                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Employee item in EmployeeList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = item.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = item.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            return View(); 
        }

        public ActionResult MyTeamSelect(string strUserIDList)
        {
            var efemployeeInfoProvider = AspNetEmployeeInfoProviderManager.Default as EFEmployeeInfoProvider;
            EmployeeInfoUnit unitinfo = efemployeeInfoProvider.GetEmployeeInfoUnit();
            JavaScriptSerializer jsonConverter = new JavaScriptSerializer();
            AspNetRoleProviderWrapper wapper = new AspNetRoleProviderWrapper();
            if (Request.IsAjaxRequest())
            {
                string str = Request["ObjectID"];
                #region  获取数据
                if (string.IsNullOrEmpty(Request["ObjectID"]))
                {
                    string Key = Request["Key"];
                    IList<MyTeam> MyTeam = respository.GetAllMyTeam( this.UserID);
                    IList<Employee> EmployeeList = new List<Employee> ();
                    foreach (var i in MyTeam)
                    {
                        Employee save = new Employee();
                        save = GetEmployeeByUserKey(i.UserID.Value);
                        EmployeeList.Add(save);
                    }
                    IList<EmployeeSelectModel> EmployeeModelList = new List<EmployeeSelectModel>();
                    foreach (Employee item in EmployeeList)
                    {
                        KeyValueModel keyValueModel = new KeyValueModel()
                        {
                            Key = item.EMPCode,
                            Value = "Employee"
                        };
                        EmployeeSelectModel model = new EmployeeSelectModel()
                        {
                            HasChildren = false,
                            ObjectID = jsonConverter.Serialize(keyValueModel),
                            Type = "Employee",
                            Name = item.ChineseName,
                            spriteCssClass = "treeView_Employee",
                            UserID = item.UserID
                        };
                        EmployeeModelList.Add(model);
                    }
                    JsonResult result = new JsonResult();
                    result.Data = EmployeeModelList;
                    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    return result;
                }
                #endregion
            }
            return View();
        }




    }
}
